﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;


public class OrderDetails
{
    public string ProductName { get; set; }
    public decimal Price { get; set; }//decimal更为精确
    public int Quantity { get; set; }
    public OrderDetails()
    { }
    public OrderDetails(string productName, decimal price, int quantity)
    {
        ProductName = productName;
        Price = price;
        Quantity = quantity;
    }

    public decimal GetTotalPrice()
    {
        return Price * Quantity;
    }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())//!(obj is OrderDetails)
        {
            return false;
        }

        OrderDetails other = obj as OrderDetails;
        return ProductName == other.ProductName && Price == other.Price && Quantity == other.Quantity;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(ProductName, Price, Quantity);
    }

    public override string ToString()
    {
        return $"ProductName: {ProductName}, Price: {Price}, Quantity: {Quantity}";
    }
}


public class Order
{
    public int OrderId { get; set; } //订单号
    public string Customer { get; set; } //商品名称
    public List<OrderDetails> Details { get; set; } = new List<OrderDetails>();//包含商品名称，订单金额

    public Order() // 无参数的构造函数
    {
        Details = new List<OrderDetails>();
    }

    public Order(int orderId, string customer)
    {
        OrderId = orderId;
        Customer = customer;
    }

    public decimal GetTotalAmount()
    {
        return Details.Sum(d => d.GetTotalPrice());
    }

    public void AddOrderDetail(OrderDetails detail)
    {
        if (Details.Contains(detail))
        {
            throw new Exception("Order detail already exists.");
        }
        Details.Add(detail);
    }

    public override bool Equals(object obj)
    {
        if (!(obj is Order))
        {
            return false;
        }

        Order other = (Order)obj;
        return OrderId == other.OrderId;
    }

    public override int GetHashCode()
    {
        return OrderId;
    }

    public override string ToString()
    {
        var stringBuilder = new System.Text.StringBuilder();//使用var便于维护
        foreach (var detail in Details)
        {
            stringBuilder.Append(detail.ToString());
            stringBuilder.Append("\n");
        }
        string details = stringBuilder.ToString();
        return $"OrderId: {OrderId}, Customer: {Customer}, TotalAmount: {GetTotalAmount()}\nDetails:\n{details}";
    }
}


public class OrderService
{
    private List<Order> orders = new List<Order>();
    public List<Order> GetOrders()//方便单元测试
    {
        return orders;
    }

    public void AddOrder(Order order)
    {
        if (orders.Any(o => o.Equals(order)))
        {
            throw new Exception("Order already exists.");
        }
        orders.Add(order);
    }

    public void RemoveOrder(int orderId)
    {
        var matchedOrders = orders.Where(o => o.OrderId == orderId).ToList();
        if (matchedOrders.Count == 0)
        {
            throw new Exception("Order does not exist.");
        }
        foreach (var order in matchedOrders)
        {
            orders.Remove(order);
        }
    }

    public void UpdateOrder(Order updatedOrder)
    {
        var orderIndex = orders.FindIndex(o => o.OrderId == updatedOrder.OrderId);
        if (orderIndex == -1)
        {
            throw new Exception("Order does not exist.");
        }
        orders[orderIndex] = updatedOrder;
    }

    public IEnumerable<Order> QueryOrdersByCustomer(string customer)
    {
        return orders.Where(o => o.Customer == customer).OrderBy(o => o.GetTotalAmount());
    }

    public IEnumerable<Order> QueryOrdersByProduct(string productName)
    {
        return orders.Where(o => o.Details.Any(d => d.ProductName == productName)).OrderBy(o => o.GetTotalAmount());
    }

    public void SortOrders(Func<Order, object> keySelector)//自定义排序
    {
        orders = orders.OrderBy(keySelector).ToList();
    }

    public void SortOrders()
    {
        orders.Sort((o1, o2) => o1.OrderId.CompareTo(o2.OrderId));//直接使用int类型的CompareTo方法
    }

    public override string ToString()
    {
        return string.Join("\n\n", orders.Select(o => o.ToString()));
    }
    public void ExportOrders(string filename)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
        using (StreamWriter writer = new StreamWriter(filename))
        {
            serializer.Serialize(writer, orders);
        }
    }
    public List<Order> ImportOrders(string filename)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
        using (StreamReader reader = new StreamReader(filename))
        {
            return (List<Order>)serializer.Deserialize(reader);
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        var orderService = new OrderService();

        // 初始化
        var order1 = new Order(1, "Customer1");
        order1.AddOrderDetail(new OrderDetails("Product1", 10.0m, 2));
        order1.AddOrderDetail(new OrderDetails("Product2", 15.5m, 1));
        orderService.AddOrder(order1);

        var order2 = new Order(2, "Customer2");
        order2.AddOrderDetail(new OrderDetails("Product3", 25.0m, 1));
        orderService.AddOrder(order2);

        // 打印所有订单
        Console.WriteLine("All Orders:");
        Console.WriteLine(orderService);

        string filename = "orders.xml";
        orderService.ExportOrders(filename);
        orderService.ImportOrders("orders.xml");

        Console.WriteLine("Imported Orders:");
        Console.WriteLine(orderService);
    }
}
